<template> 
<div class="container">
  <van-cell>
    <template #title>
      <span class="van-cell--required">{{ title+limitTitle }}</span>
      <br />
      <div class="van-cell__label">{{smallTitle}}</div>
    </template>
    <template #label> 
      <van-uploader type="file" v-model="files"  :after-read="afterRead" :before-delete="beforeDelete" :max-count="maxCount" :preview-size="[80, 80]"  accept="image/*" multiple />
    </template>
  </van-cell>

  <van-button round type="primary" @click="uploadFileFunc">上传文件</van-button> 
</div>
<div class="van-multi-ellipsis--l5">
  温馨提示：后端接口未部署，使用时请参照/api/uploadfileApi.ts 文件中的uploadFile 接口描述，对接后端文件上传接口即可
</div>
 
</template>
 

<script lang="ts" setup>
import { uploadFile,getFileList } from '../../api/userInfoApi'
import { onMounted, reactive, ref } from 'vue'; 
import { ImagePreview,Dialog,Toast } from "vant"  

const smallTitle: string = '';//副标题
const title: string = '上传测试';
const limitTitle: number = 2; 
const maxCount = 4;

const files = ref<any[]>([]);//用于展示图片
const uploadImage:File[] = []; //用于提交图片
const previewImgDialog :any=ref();
const imgFile :any = reactive({
  status:"success",
  message:"",
});

onMounted(() => {  
  getFileShow() 
})
 
//点击上传图片
const uploadFileFunc = async () => {  
  if(!uploadImage){
    Toast('请上传图片');
  }
  let formdata = new FormData();
  if (uploadImage instanceof Array && uploadImage.length) {
    uploadImage.forEach((item, i) => { 
      formdata.append('files[' + i + ']', item)
    })
  } else {
    formdata.append('files[0]', uploadImage[0])
  }
  formdata.append('keyTest', '1234');
  const aaa = await uploadFile(formdata);
  console.log('aaa==============>', aaa);
}

const afterRead = (data: any) => {
  data.status = 'uploading';
  data.message = '上传中...';
  if (data instanceof Array && data.length) {
    data.forEach(item => {
      uploadImage.push(item.file)
    })
  } else {
    uploadImage.push(data.file)
  }
  setTimeout(() => {
    data.status = 'success';
    data.message = '上传成功';
  }, 1000);
}

//删除方法
const beforeDelete = (data: any, detail: any) => {
  uploadImage.splice(detail.index, 1);
  files.value.splice(detail.index, 1);
}

// 点击图片预览
const previewImg = (images: any,index:number) => {
  previewImgDialog.value = ImagePreview({
    images: images.map((v: any) => v.content), //需要预览的图片 URL 数组
    showIndex: true, //是否显示页码
    loop: false,//是否开启循环播放
    closeOnPopstate: true, //是否在页面回退时自动关闭
    startPosition: index,  //图片预览起始位置索引
    onClose() { }
  })
}
 
//图片预览
const getFileShow = async () => {
 //const fileEntity =  {file:{},status:"",message:"",content:""};
 getFileList({}).then(rest => {
    if (rest.data instanceof Array && rest.data.length > 0) {
      rest.data.forEach((item, i) => {
        var fl = getFile(item,'test_image' + (i+1)); 
        uploadImage.push(fl);   
        Object.assign(imgFile, { file:fl, content: getBase64(item)});      
        files.value.push(imgFile);         
      })
    }
  }); 
}
//base64 字符串转File
const getFile = (base64: any, fileName: string): File => {
  var changebase64 = "data:image/jpg;base64," + base64.replace(/[\r\n]/g, "");
  const _blob = b64toBlob(changebase64); 
  var _file = new File([_blob], fileName + '.jpg', { type: 'image/jpeg' });
  return _file;
}
//base64 字符串转Blob
const b64toBlob = (dataURI: string): Blob => {
  var byteString = window.atob(dataURI.split(',')[1]);
  var ab = byteString.length;
  var ia = new Uint8Array(ab);
  for (var i = 0; i < ab; i++) {
    ia[i] = byteString.charCodeAt(i);
  } 
  var theBlob = new Blob([ia], { type: 'image/jpeg' });  
  return theBlob;
}
//获取base64 字符串
const getBase64 = (base64: any): string => {
  return "data:image/jpg;base64," + base64.replace(/[\r\n]/g, ""); 
}
 

</script>

<style lang="scss" scoped>
 .container {
  padding: 10px 10px; 
  &-item {
    padding: 7px 0px;
  }
  &-btn {
    padding: 7px 10px;
  }
}
.van-button__content{
  background-color: blue;
}
</style>
